package com.ccteam.shared.domain.moment

import android.content.Context
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.map
import com.ccteam.model.moment.MOMENT_SHARE_TYPE_NONE
import com.ccteam.model.moment.MomentShareVO
import com.ccteam.shared.api.MomentsDataSource
import com.ccteam.shared.data.moment.MomentsPagingSource
import com.ccteam.shared.domain.PagingUseCase
import com.ccteam.shared.result.moment.MomentListItem
import com.ccteam.shared.utils.*
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/28
 *
 * 朋友圈首页Domain层
 */
class MomentsHomeDataUseCase @Inject constructor(
    @ApplicationContext private val context: Context,
    private val momentsDataSource: MomentsDataSource
): PagingUseCase<Nothing?, MomentListItem>(
    Dispatchers.IO
) {
    override fun execute(parameters: Nothing?): Flow<PagingData<MomentListItem>> {
        return Pager(
            PagingConfig(pageSize = 15,initialLoadSize = 15)
        ){
            MomentsPagingSource(momentsDataSource)
        }.flow.map { pagingData ->
            pagingData.map {
                MomentListItem(it.id,it.userMomentVO.id,
                    it.userMomentVO.name,
                    it.userMomentVO.photoUrl + PHOTO_QUALITY,
                    it.createTime.transToDateReciprocal(context),it.content, it.images.map { momentImage ->
                       MomentListItem.MomentImageItem(momentImage.id,momentImage.momentId,momentImage.url + MOMENT_QUALITY)
                    },
                    transformToMomentShareItem(it.momentShareVO,it.type,it.shareId),it.upNum,it.commentNum)
            }
        }
    }

    private fun transformToMomentShareItem(momentShareVO: MomentShareVO?,
                                           type: Int, shareId: String?): MomentListItem.MomentShareItem?{
        if(type == MOMENT_SHARE_TYPE_NONE || momentShareVO == null || shareId == null){
            return null
        }
        return MomentListItem.MomentShareItem(
            shareId,type,momentShareVO.title ?: EMPTY_STRING,
            momentShareVO.subTitle ?: EMPTY_STRING,
            momentShareVO.imgUrl + ALBUM_QUALITY
        )

    }
}